#!/bin/sh
NAME="$1"
USER="$2"
PASSWORD="$3"

cd /passwds || exit 1

if [ -z "$NAME" ]; then
    echo "Service name must be defined" 1>&2
    exit 1
elif [ -f $NAME.htpasswd ]; then
    echo "$NAME.htpasswd exists, aborting" 1>&2
    exit 1
fi

if [ -z "$USER" ]; then
    echo "User must be defined" 1>&2
    exit 1
fi

if [ -z "$PASSWORD" ]; then
    PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 20 | head -n 1`
    echo "Password was not defined, generating a random one..."
fi

echo -n $USER:`openssl passwd -apr1 $PASSWORD` >> $NAME.htpasswd
chown $UID:$GID $NAME.htpasswd
chmod 640 $NAME.htpasswd

echo
echo  "A new password file has been saved to /passwds/$NAME.htpasswd :"
echo  "- Service  :  $NAME"
echo  "- User     :  $USER"
echo  "- Password :  $PASSWORD"
echo
echo  "Paste this to your vhost in order to enable auth :"
echo  "        auth_basic \"Who's this?\";"
echo  "        auth_basic_user_file /passwds/$NAME.htpasswd;"
echo
echo "Done."

exit 0
